"""
宏观经济数据API路由
"""

from fastapi import APIRouter, Depends
from typing import List
from datetime import date
from sqlalchemy.orm import Session

from src.models.base import get_db
from src.models.macro import (
    MacroGDP,
    MacroCPI,
    MacroPMI,
    MacroMoneySupply
)

router = APIRouter(prefix="/macro", tags=["宏观经济"])

@router.get("/gdp", response_model=List[dict])
def get_gdp(
    start_year: int = None, 
    end_year: int = None,
    db: Session = Depends(get_db)
):
    """获取GDP数据"""
    query = db.query(MacroGDP)
    if start_year:
        query = query.filter(MacroGDP.quarter >= f"{start_year}-01-01")
    if end_year:
        query = query.filter(MacroGDP.quarter <= f"{end_year}-12-31")
    return [{
        "quarter": gdp.quarter.strftime("%Y-Q%q"),
        "gdp": float(gdp.gdp),
        "primary": float(gdp.primary),
        "secondary": float(gdp.secondary),
        "tertiary": float(gdp.tertiary)
    } for gdp in query.order_by(MacroGDP.quarter).all()]

@router.get("/cpi", response_model=List[dict])
def get_cpi(
    start_date: date = None,
    end_date: date = None,
    db: Session = Depends(get_db)
):
    """获取消费者价格指数"""
    query = db.query(MacroCPI)
    if start_date:
        query = query.filter(MacroCPI.month >= start_date)
    if end_date:
        query = query.filter(MacroCPI.month <= end_date)
    return [{
        "month": cpi.month.strftime("%Y-%m"),
        "cpi": float(cpi.cpi)
    } for cpi in query.order_by(MacroCPI.month).all()]

@router.get("/pmi", response_model=List[dict])
def get_pmi(
    period: str = None,
    db: Session = Depends(get_db)
):
    """获取采购经理指数"""
    query = db.query(MacroPMI)
    if period:
        query = query.filter(MacroPMI.period.like(f"%{period}%"))
    return [{
        "period": pmi.period,
        "manufacturing": float(pmi.manufacturing),
        "non_manufacturing": float(pmi.non_manufacturing)
    } for pmi in query.order_by(MacroPMI.period).all()]